
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="微信小程序,">
  

  
    <meta name="description" content="微信小程序打夯之旅(二)：Cookie模拟">
  
  
  <link rel="icon" type="image/x-icon" href="/logo.png">
  <title>微信小程序打夯之旅(二)：Cookie模拟 [ 复制粘贴工程师 ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="https://wx.qlogo.cn/mmopen/vi_32/AMpRacDgkTPogKk4gQ5IC3QezP55XoPpicQpnD9Vz3eNz6OPFYyFrFzCa4EGQGH65kPia5YJwQBBvvJpVwQ4lfVg/132">
    <span class="title">复制粘贴工程师</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
  </ul>

</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        微信小程序打夯之旅(二)：Cookie模拟
      </h1>
      <span>
        
        <time class="time" datetime="2019-03-20T09:01:13.000Z">
        2019-03-20
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/微信小程序/">微信小程序</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <p>众所可能周知，微信小程序是不支持 <code>cookie</code> 的，这就非常影响前后端的沟通，所以不得不自己实现一套 <code>cookie</code> 机制了。</p>
<a id="more"></a>
<h3 id="使用方式"><a href="#使用方式" class="headerlink" title="使用方式"></a>使用方式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> cookie <span class="keyword">from</span> <span class="string">'../plugins/cookie.js'</span>;</span><br><span class="line"></span><br><span class="line">cookie.getAllString() <span class="comment">// 获取cookie字符串</span></span><br><span class="line">cookie.get(<span class="string">'key'</span>) <span class="comment">// 获取某个cookie值</span></span><br><span class="line">cookie.set(<span class="string">'key'</span>, <span class="string">'value'</span>)  <span class="comment">// 设置一个新的cookie值</span></span><br><span class="line">cookie.delete(<span class="string">'key'</span>)  <span class="comment">//删除某个cookie值</span></span><br><span class="line">cookie.clear()  <span class="comment">// 清空cookie</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 在http请求头部的使用：设置请求中的cookie值</span></span><br><span class="line">opt.header = <span class="built_in">Object</span>.assign(opt.header || &#123;&#125;, &#123;</span><br><span class="line">  Cookie: cookieUtil.getAllString(),</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在http请求回调的使用：设置回调中的cookie值</span></span><br><span class="line"><span class="keyword">const</span> setCookieStr = res.header[<span class="string">'Set-Cookie'</span>] || res.header[<span class="string">'set-cookie'</span>];</span><br><span class="line">setCookieStr &amp;&amp; cookie.parseSetCookie(setCookieStr);</span><br></pre></td></tr></table></figure>
<h3 id="原理解读-cookie-js"><a href="#原理解读-cookie-js" class="headerlink" title="原理解读 - cookie.js"></a>原理解读 - cookie.js</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 利用 storage 模拟 cookie 操作</span></span><br><span class="line"><span class="comment"> * 请求等情况下数据要求较高，所以需要同步操作</span></span><br><span class="line"><span class="comment"> * cookie 存储格式：&#123; key: &#123; value: 'value', expires: 1526452752000 &#125; &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> storageKey = <span class="string">'reqCookie'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Fn = &#123;</span><br><span class="line">  <span class="comment">// 获取 cookie 字符串</span></span><br><span class="line">  getAllString() &#123;</span><br><span class="line">    <span class="keyword">const</span> cookie = <span class="keyword">this</span>._getAll();</span><br><span class="line">    <span class="keyword">const</span> deleteArr = [];</span><br><span class="line">    <span class="keyword">const</span> result = [];</span><br><span class="line">    <span class="built_in">Object</span>.keys(cookie).forEach(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">typeof</span> cookie[key] !== <span class="string">'object'</span> || <span class="keyword">this</span>._checkExpires(cookie[key]) || !cookie[key].value) &#123;</span><br><span class="line">        deleteArr.push(key);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        result.push(<span class="string">`<span class="subst">$&#123;key&#125;</span>=<span class="subst">$&#123;cookie[key].value&#125;</span>`</span>);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">this</span>.batchDelete(deleteArr);</span><br><span class="line">    <span class="keyword">return</span> result.join(<span class="string">'; '</span>);</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 获取 cookie 中一个字段</span></span><br><span class="line">  <span class="keyword">get</span>(key) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!key) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> cookie = <span class="keyword">this</span>._getAll();</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>._checkExpires(cookie[key]) || <span class="keyword">typeof</span> cookie[key] !== <span class="string">'object'</span>) &#123;</span><br><span class="line">      <span class="keyword">this</span>.delete(key);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cookie[key] &amp;&amp; cookie[key].value;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 设置 cookie 中一个字段</span></span><br><span class="line">  <span class="keyword">set</span>(key, value) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!key) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> cookie = <span class="keyword">this</span>._getAll();</span><br><span class="line">      cookie[key] = <span class="keyword">typeof</span> value === <span class="string">'object'</span> ? value : &#123; value &#125;;</span><br><span class="line">      wx.setStorageSync(storageKey, <span class="built_in">JSON</span>.stringify(cookie));</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">      <span class="built_in">console</span>.error(e);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 设置 cookie 多个字段</span></span><br><span class="line">  batchSet(obj) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!obj || <span class="keyword">typeof</span> obj !== <span class="string">'object'</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> cookie = <span class="keyword">this</span>._getAll();</span><br><span class="line">      <span class="built_in">Object</span>.keys(obj).forEach(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">        obj[key] = <span class="keyword">typeof</span> obj[key] === <span class="string">'object'</span> ? obj[key] : &#123; <span class="attr">value</span>: obj[key] &#125;;</span><br><span class="line">      &#125;);</span><br><span class="line">      <span class="built_in">Object</span>.assign(cookie, obj);</span><br><span class="line">      wx.setStorageSync(storageKey, <span class="built_in">JSON</span>.stringify(cookie));</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">      <span class="built_in">console</span>.error(e);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 删除 cookie 中一个字段</span></span><br><span class="line">  <span class="keyword">delete</span>(key) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!key) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> cookie = <span class="keyword">this</span>._getAll();</span><br><span class="line">      cookie[key] &amp;&amp; (<span class="keyword">delete</span> cookie[key]);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">      wx.setStorageSync(storageKey, <span class="built_in">JSON</span>.stringify(cookie));</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">      <span class="built_in">console</span>.error(e);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 删除 cookie 多个字段</span></span><br><span class="line">  batchDelete(keyArr) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!keyArr || !keyArr.length) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> cookie = <span class="keyword">this</span>._getAll();</span><br><span class="line">      keyArr.forEach(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">        cookie[key] &amp;&amp; (<span class="keyword">delete</span> cookie[key]);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">      &#125;);</span><br><span class="line">      wx.setStorageSync(storageKey, <span class="built_in">JSON</span>.stringify(cookie));</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">      <span class="built_in">console</span>.error(e);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 清除 cookie</span></span><br><span class="line">  clear() &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      wx.setStorageSync(storageKey, <span class="string">'&#123;&#125;'</span>);</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">      <span class="built_in">console</span>.error(e);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 解析 set-cookie</span></span><br><span class="line">  parseSetCookie(str) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!str) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> expiresReg = <span class="regexp">/expires=([^;]+);/gi</span>;</span><br><span class="line">    <span class="keyword">const</span> setCookieStr = str.replace(expiresReg, (match, time) =&gt; <span class="string">`expires=<span class="subst">$&#123;<span class="keyword">new</span> <span class="built_in">Date</span>(time).getTime()&#125;</span>;`</span>).replace(<span class="regexp">/\s+/gi</span>, <span class="string">''</span>);</span><br><span class="line">    <span class="keyword">const</span> cookieObj = &#123;&#125;;</span><br><span class="line">    setCookieStr.split(<span class="string">','</span>).forEach(<span class="function"><span class="params">cookieStr</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">let</span> key;</span><br><span class="line">      cookieStr.split(<span class="string">';'</span>).forEach(<span class="function">(<span class="params">part, index</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          <span class="keyword">const</span> cArr = part.split(<span class="string">'='</span>);</span><br><span class="line">          <span class="keyword">if</span> (index === <span class="number">0</span>) &#123;</span><br><span class="line">            key = cArr[<span class="number">0</span>];</span><br><span class="line">            cookieObj[key] = &#123; <span class="attr">value</span>: cArr[<span class="number">1</span>] &#125;;</span><br><span class="line">          &#125; <span class="keyword">else</span> <span class="keyword">if</span> (cArr[<span class="number">0</span>] === <span class="string">'expires'</span>) &#123;</span><br><span class="line">            cookieObj[key].expires = cArr[<span class="number">1</span>];</span><br><span class="line">          &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">          <span class="built_in">console</span>.error(e);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">this</span>.batchSet(cookieObj);</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 检查 cookie 是否过期</span></span><br><span class="line">  _checkExpires(valueObj) &#123;</span><br><span class="line">    <span class="keyword">return</span> valueObj &amp;&amp; valueObj.expires &amp;&amp; <span class="built_in">Date</span>.now() &gt; valueObj.expires;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 获取 cookie 对象</span></span><br><span class="line">  _getAll() &#123;</span><br><span class="line">    <span class="keyword">let</span> cookie = &#123;&#125;;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> storage = wx.getStorageSync(storageKey);</span><br><span class="line">      cookie = storage ? <span class="built_in">JSON</span>.parse(storage) : &#123;&#125;;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">      <span class="built_in">console</span>.error(e);  <span class="comment">// eslint-disable-line</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cookie;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Fn;</span><br></pre></td></tr></table></figure>
    </div>

    <div>全文完。</div>
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用方式"><span class="toc-text">使用方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#原理解读-cookie-js"><span class="toc-text">原理解读 - cookie.js</span></a></li></ol>
  </div>


  </div>
</div>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share" style="width: 100%;">
  <!-- <img src="https://kevinofneu-blog-static.oss-cn-beijing.aliyuncs.com/static/2018-12-10-qrcode_for_gh_ffacf5722095_258.jpg" alt="Running Geek" style="margin: auto; display: block;"/>

  <div style="margin: auto; text-align: center; font-size: 0.8em; color: grey;">老铁们关注走一走，不迷路</div> -->

</div>

  
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2019/03/20/微信小程序登录流程/" rel="next" title="微信小程序打夯之旅(一)：登录流程">
          微信小程序打夯之旅(一)：登录流程
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2019/03/20/微信小程序http封装/" rel="prev" title="微信小程序打夯之旅(三)：Http封装">
            微信小程序打夯之旅(三)：Http封装
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


    </div>

    
    <div id="vcomments" style="max-width: 800px; margin: 16px auto;"></div>
  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="/">首页</a> |
        <a class="bottom-item" href="https://github.com/TJ-XiaJiaHao" target="_blank">GitHub</a> |
        <a class="bottom-item">联系邮箱：1452806@tongji.edu.cn</a>
    </div>
</footer>
  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
<script type="text/javascript">
  new Valine({
    el: '#vcomments',
    appId: '8CwYqXS8IoFbvaA9PmgqGjTf-gzGzoHsz',
    appKey: 'z5bVoSPDPhd8hzlXvDey5Hpz',
    verify:false,
    placeholder: '评论留言'
  })
</script>
</html>
